// Proxy 对象

const person = {
  name: 'zce',
  age: 20
}

const personProxy = new Proxy(person, {
  // 监视属性访问
  get (target, property) {
    // console.log(target, property)
    // 添加访问逻辑
    return property in target ? target[property] : 'default'
    // return 100
  },
  // 监视属性设置
  set (target, property, value) {
    // 添加设置判断
    if (property === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError(`${value} is not an int`)
      }
    }

    target[property] = value
    console.log(target, property, value)
  },
  // 相比Object.defineProperty，Proxy 可以监视读写以外的操作
  deleteProperty (target, property) {
    console.log('delete', property)
    delete target[property]
  }
})

console.log(personProxy.age1)
personProxy.age = 18
delete personProxy.age
console.log(person)


// Proxy 可以很方便的监视数组操作 --------------------------

const list = []

const listProxy = new Proxy(list, {
  set (target, property, value) {
    console.log('set', property, value)
    target[property] = value
    return true
  }
})

listProxy.push(100)
listProxy.push(100)

// 优势3：Proxy 不需要侵入对象 --------------------------
// defineProperty的方式会对原对象进行修改

const person2 = {}

Object.defineProperty(person2, 'name', {
  get () {
    console.log('name 被访问')
    return person._name
  },
  set (value) {
    console.log('name 被设置')
    person._name = value
  }
})
Object.defineProperty(person2, 'age', {
  get () {
    console.log('age 被访问')
    return person._age
  },
  set (value) {
    console.log('age 被设置')
    person._age = value
  }
})

person2.name
